import { NextResponse } from 'next/server';
import { registerUser } from '@/lib/db';

export async function POST(request: Request) {
  try {
    const { username, email, password } = await request.json();

    if (!username || !email || !password) {
      return NextResponse.json(
        { error: '用户名、邮箱和密码都是必填项' },
        { status: 400 }
      );
    }

    if (password.length < 6) {
      return NextResponse.json(
        { error: '密码长度至少为6位' },
        { status: 400 }
      );
    }

    const user = registerUser(username, email, password);

    // 不要将密码发送到客户端
    const { password: _, ...userWithoutPassword } = user;

    return NextResponse.json({ 
      user: userWithoutPassword,
      message: '注册成功' 
    }, { status: 201 });
  } catch (error: any) {
    if (error.message === 'Username or email already exists') {
      return NextResponse.json(
        { error: '用户名或邮箱已存在' },
        { status: 409 }
      );
    }
    
    console.error('Registration error:', error);
    return NextResponse.json(
      { error: '注册过程中发生错误' },
      { status: 500 }
    );
  }
}